<template>
  <div class="closing">
    <div>
      <el-button size="mini" @click="handleGetUntreated">{{ $t('btn.reload') }}</el-button>
      <el-button type="primary" size="mini" @click="isClosingDialog=true">{{ $t('market.filter') }}</el-button>
      <el-button type="primary" size="mini" @click="isCalculaDialog=true">{{ $t('market.calculation') }}<!--重新归集--></el-button>
      <el-button type="primary" size="mini" @click="handleExport">{{ $t('btn.toExcel') }}</el-button>
    </div>
    <div class="table-content">
      <jc-table
        v-loading="loading"
        :table-data="tableData"
        :table-header="tableHeader"
        :table-height="tableHeight"
        table-selection
        sortable
        :get-summaries="getSummaries"
        show-summary
        @selectionChange="selectionDatas"
      >
        <!--   自定义金额  -->
        <template v-slot:btnSlot="col">
          <el-input v-model.number.trim="col.scope.row.frealamount" disabled />
        </template>
        <!--    操作    -->
        <template v-slot:btnState="col">
          <!--          <el-button type="primary" size="mini" @click="editCollection(col.scope.row)">{{ $t('btn.edit') }}</el-button>-->
          <el-button type="primary" size="mini" @click="examine(col.scope.row)">
            {{ $t('market.examine') }}<!--查看-->
          </el-button>
        </template>
      </jc-table>
    </div>
    <!--    分页器-->
    <div class="footer">
      <jc-pagination
        :total="subDetails.total"
        :page.sync="subDetails.pageNum"
        :limit.sync="subDetails.pageSize"
        @pagination="handleGetUntreated"
      />
    </div>
    <!-- 费用归集 过滤-->
    <el-dialog
      v-dialogDrag
      :title="$t('market.collection')"
      model
      :visible.sync="isClosingDialog"
      :close-on-click-modal="false"
      width="600px"
      center
    >
      <div>
        <el-form :model="subDetails" size="mini" label-width="100px">
          <el-form-item :label="$t('market.accountingyear')">
            <el-select
              v-model="subDetails.faccountingyear"
            >
              <el-option v-for="item in yearData" :key="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('market.accountingmonth')">
            <el-select
              v-model="subDetails.faccountingmonth"
            >
              <el-option v-for="item in 12" :key="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('market.seeaname')">
            <el-input v-model.trim="subDetails.fseeaname" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.policyname')">
            <el-input v-model.trim="subDetails.fpolicyname" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.expenseite')">
            <el-input v-model.trim="subDetails.ftypename">
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="sujectOpen('费用项目')"
              />
            </el-input>
          </el-form-item>
          <el-form-item :label="$t('market.prodept')">
            <el-input v-model.trim="subDetails.fdeptname">
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="sujectOpen('部门')"
              />
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isClosingDialog = false">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" @click="initialCon">{{ $t('btn.confirm') }}</el-button>
      </div>
    </el-dialog>
    <!-- 费用归集 详情 -->
    <el-dialog
      v-dialogDrag
      :title="$t('market.collectionDetail')"
      model
      :visible.sync="isSourceDialog"
      :close-on-click-modal="false"
      width="60%"
      center
    >
      <div style="margin-bottom: 5px">
        <span style="width: 100px;">凭证编码</span>
        <el-input v-model="voucherNumber" size="mini" style="width: 167px" />
        <el-button style="margin-left: 10px" size="mini" type="primary" @click="examine">{{ $t('btn.search') }}</el-button>
      </div>
      <div>
        <jc-table
          :table-data="sourceData"
          :table-header="sourceHeader"
          table-height="500px"
          serial
        >
          <template v-slot:billSlot="col">
            <el-link type="primary" @click="pushVoucher(col.scope.row)">{{ col.scope.row.voucherNumber }}</el-link>
          </template>
        </jc-table>
      </div>
      <div class="footer">
        <jc-pagination
          :total="total"
          :page.sync="pageNum"
          :limit.sync="pageSize"
          @pagination="examine"
        />
      </div>
    </el-dialog>
    <!-- 重新归集 -->
    <el-dialog
      v-dialogDrag
      :title="$t('market.calculation')"
      model
      :visible.sync="isCalculaDialog"
      :close-on-click-modal="false"
      width="400px"
      center
    >
      <div>
        <el-form :model="calculaData" size="mini" label-width="100px">
          <el-form-item :label="$t('market.period')">
            <el-date-picker
              v-model="calculaData.fdate"
              type="month"
              value-format="yyyy-MM"
            />
          </el-form-item>
          <el-form-item :label="$t('market.subjectName')">
            <el-input v-model.trim="calculaData.subjectName">
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="isSubListVisibled=true"
              />
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isCalculaDialog = false">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" @click="calculation">{{ $t('btn.confirm') }}</el-button>
      </div>
    </el-dialog>
    <!--    科目列表-->
    <subjectList v-if="isSubListVisibled" @subject="sublistData" />
    <!-- 维度 -->
    <dimen v-if="isDimenDataVisibled" :dimen-list="dimenList" @dimen="dimenData" />
  </div>
</template>

<script>
import {
  costCalculation, queryCollectionSource,
  queryFinCostList, updateFinCostDetails
} from '@/api/financial/warehousing'
import dimen from '@/views/financial/costAccounting/component/dimen'
import { export_json_to_excel, formatJson } from '@/utils/Export2Excel'
import { querySubjectDetails } from '@/api/financial/subject'
import subjectList from '@/views/financial/voucherTemplate/components/subjectList'

export default {
  name: 'CollectionList',
  components: {
    dimen,
    subjectList
  },
  data() {
    return {
      subDetails: {
        faccountingyear: 2022,
        faccountingmonth: 1,
        fseeaname: '财务会计核算体系',
        fpolicyname: '中国准则会计政策',
        ftypename: '',
        fdeptname: '',
        pageNum: 1,
        pageSize: 200,
        total: 0
      },
      calculaData: {
        fdate: ''
      },
      loading: false,
      isSubListVisibled: false,
      isCalculaDialog: false,
      isClosingDialog: false,
      isDimenDataVisibled: false,
      isSourceDialog: false,
      dimenList: '',
      dimenList1: [],
      yearData: [2019, 2020, 2021, 2022, 2023, 2024, 2025],
      // 表头
      selectData: [],
      tableData: [],
      tableHeight: '70vh',
      tableHeader: [
        { label: this.$t('market.billNo'), prop: 'fbillno', width: '120' },
        { label: this.$t('market.calculationDate'), prop: 'fdate', width: '90' },
        { label: this.$t('market.seeaname'), prop: 'fseeaname' },
        { label: this.$t('market.policyname'), prop: 'fpolicyname' },
        { label: this.$t('market.accountingyear'), prop: 'faccountingyear', width: '80' },
        { label: this.$t('market.accountingmonth'), prop: 'faccountingmonth', width: '80' },
        { label: this.$t('market.typenumber'), prop: 'ftypenumber' },
        { label: this.$t('market.typename'), prop: 'ftypename' },
        { label: this.$t('market.deptnumber'), prop: 'fdeptnumber' },
        { label: this.$t('market.deptname'), prop: 'fdeptname' },
        { label: this.$t('market.billamount'), prop: 'fcalamount', width: '100', align: 'right' },
        { label: this.$t('market.realityamount'), prop: 'frealamount', width: '100', align: 'right' },
        { label: this.$t('market.handle'), type: 'state', width: '100' }
      ],
      pageNum: 1,
      pageSize: 200,
      total: 0,
      voucherNumber: '',
      sourceData: [],
      sourceHeader: [
        { label: this.$t('market.voucherNum'), type: 'bill', prop: 'voucherNumber', width: '120' },
        { label: this.$t('market.digest'), prop: 'description' },
        { label: this.$t('market.dimensionString'), prop: 'dimensionString' },
        { label: this.$t('market.expenseite'), prop: 'fyxmName', width: '80' },
        { label: this.$t('market.amountIn'), prop: 'amountIn', width: '80' },
        { label: this.$t('market.amountOut'), prop: 'amountOut', width: '80' }
      ]
    }
  },
  created() {
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 200px)' : '73vh'
  },
  methods: {
    // 过滤 费用项目 部门
    sujectOpen(item) {
      this.dimenList = item
      this.isDimenDataVisibled = true
    },
    dimenData(ev) {
      if (ev.frealName) {
        if (this.dimenList === '费用项目') {
          this.subDetails.ftypename = ev.frealName
          this.subDetails.ftypenumber = ev.frealNumber
        } else if (this.dimenList === '部门') {
          this.subDetails.fdeptname = ev.frealName
          this.subDetails.fdeptnumber = ev.frealNumber
        }
      }
      this.isDimenDataVisibled = false
    },
    // 过滤确认
    initialCon() {
      this.isClosingDialog = false
      this.handleGetUntreated()
    },
    // 获取入库成本维护列表数据
    async handleGetUntreated() {
      this.loading = true
      const DATA = { ...this.subDetails }
      const RES = await queryFinCostList(DATA)
      if (RES.code === 0) {
        this.loading = false
        this.tableData = RES.data.array
        this.subDetails.total = RES.data.total
      } else {
        this.loading = false
        this.$confirm(RES.message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
      }
    },
    // 修改
    editCollection(row) {
      const DATA = {
        frealamount: row.frealamount,
        fentryid: row.fentryid
      }
      updateFinCostDetails(DATA).then(res => {
        if (res.code === 0) {
          this.handleGetUntreated()
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 查看明细
    examine(item) {
      this.isSourceDialog = true
      if (item.fperiod) {
        this.perDate = {
          dimensionString: item.fdeptname,
          period: item.fperiod,
          fyxmId: item.ftypeId
        }
      }
      const DATA = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        voucherNumber: this.voucherNumber,
        ...this.perDate
      }
      queryCollectionSource(DATA).then(res => {
        if (res.code === 0) {
          this.sourceData = res.data.array
          this.total = res.data.total
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 跳转凭证
    pushVoucher(ev) {
      const fid = ev.voucherId
      this.$router.push({ path: `/certificateDetail/${fid}` })
      this.isSourceDialog = false
    },
    // 重新归集
    calculation() {
      costCalculation({ ...this.calculaData }).then(res => {
        if (res.code === 0) {
          this.handleGetUntreated()
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 全选
    selectionDatas(val) {
      this.selectData = val
    },
    // 科目数据
    sublistData(item) {
      if (item.fsubjectId) {
        this.calculaData.subjectId = item.fsubjectId
        this.calculaData.subjectName = item.fname
        this.courseData(item.fsubjectId)
      }
      this.isSubListVisibled = false
    },
    // 获取科目维度
    courseData(fid) {
      querySubjectDetails({ fid }).then(res => {
        this.calculaData.dimensionList = res.data.dismensionList
      })
    },
    // 自定义合计行
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return (Number(prev) + Number(curr)).toFixed(2)
            } else {
              return prev
            }
          }, 0)
        } else {
          sums[index] = ''
        }
      })
      sums.forEach((res, index) => {
        if (Number(sums[index]) > 0) {
          sums[index] = Number(sums[index]).toLocaleString()
        } else {
          sums[index] = ''
        }
      })
      sums[0] = '合计'
      return sums
    },
    // 导出表格
    handleExport() {
      require.ensure([], () => {
        const tHeader = this.tableHeader.map((res) => {
          return res.label
        })
        const filterVal = this.tableHeader.map((res) => {
          return res.prop
        })
        if (this.tableData.length <= 0) {
          this.$message.warning('没有导出数据')
        } else {
          queryFinCostList({
            pageSize: 100000,
            pageNum: 1,
            ...this.subDetails
          }).then(res => {
            if (res.code === 0) {
              const list = res.data.array
              const data = formatJson(filterVal, list)
              export_json_to_excel(tHeader, data, '费用归集明细表')
            } else {
              this.$confirm(res.message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
              })
            }
          })
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.closing {
  @include listBom;

  .header{
    margin-top: 10px;
    .header-name{
      span {
        width: 100px;
        margin-right: 10px;
        text-align: right;
      }
    }
  }
}
</style>
